package net.dubboclub.http.netty;

import io.netty.channel.Channel;

import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by bieber on 16/3/8.
 * 用于记录channel的读写时间,便于回收空闲的channel,因为是keep-alive,所以channel会存在重复使用
 * 但是为了保证有效的连接,会回收部分空闲的channel
 */
public class ChannelHolder {

    private Channel channel;

    private static AtomicLong lastRead = new AtomicLong(0l);

    private static AtomicLong lastWrite = new AtomicLong(0l);

    public ChannelHolder(Channel channel) {
        this.channel = channel;
    }

    public void read(){
        long lastReadTime = lastRead.get();
        long currentTime=System.currentTimeMillis();
        while(!lastRead.compareAndSet(lastReadTime,currentTime)){
            lastReadTime = lastRead.get();
        }
    }


    @Override
    public int hashCode() {
        return channel.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if(obj==null){
            return false;
        }
        if(obj.getClass()==ChannelHolder.class){
            ChannelHolder other = (ChannelHolder) obj;
            if(other.channel.equals(channel)){
                return true;
            }
            return false;
        }else if(obj.getClass()==Channel.class){
            Channel otherChannel = (Channel) obj;
            return otherChannel.equals(channel);
        }else{
            return false;
        }
    }

    public void write(){
        long lastWriteTime = lastWrite.get();
        long currentTime=System.currentTimeMillis();
        while(!lastWrite.compareAndSet(lastWriteTime,currentTime)){
            lastWriteTime = lastWrite.get();
        }
    }

    public long lastReadTime(){
        return lastRead.get();
    }

    public long lastWriteTime(){
        return lastWrite.get();
    }

    public Channel channel(){
        return channel;
    }



}
